import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getRole } from '@/utils/auth'
import { bratchchapter } from './api/chapters'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist白名单，不需要登录信息就可以直接访问

router.beforeEach(async(to, from, next) => {
  // start progress bar开始进度条
  NProgress.start()
  // set page title 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  // 通过 auth.js 中的 getToken 取得登录时发放的 token 信息
  const hasToken = getToken()
  // 如果取到了令牌则说明用户已经登录
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // 如果有用户的信息，则对将要访问的路由放行
      if (hasGetUserInfo) {
        var a = to.meta.role
        var quanxian = false
        for (const element in a) {
          if (quanxian === false) {
            // console.log(getRole().indexOf(a[element]))
            if (getRole().indexOf(a[element]) !== -1) {
              next()
              quanxian = true
              // 进行权限验证，有权限的才能进入下一个页面。
              // to.meta.role全部遍历完后，如果没有达到 getRole().indexOf(element) !== -1 的要求则无法跳转
              break
            }
          }
        }
        if (quanxian === false) {
          Message.error('没有访问权限')
        }
        NProgress.done()
      } else {
        // 否则要获取用户的信息
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          // remove token and go to login page to re-login删除令牌，进入登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
